package main

import (
	"encoding/hex"
	"errors"
	"flag"
	"io/ioutil"
	"os"
	"strings"

	"github.com/golang/snappy"
)

var (
	decode = flag.Bool("d", false, "decode from hex snappy")
	encode = flag.Bool("e", false, "encode to hex snappy")
	lower  = flag.Bool("lower", false, "hex encode lower")
)

func codec() error {
	flag.Parse()
	if *decode == *encode {
		return errors.New("exactly one of -d or -e must be given")
	}

	in, err := ioutil.ReadAll(os.Stdin)
	if err != nil {
		return err
	}

	var out string
	switch {
	case *decode:
		if string(in[0:2]) == "0x" {
			in = in[2:]
		}
		in, err = hex.DecodeString(string(in))
		if err != nil {
			return err
		}
		outBytes, err := snappy.Decode(nil, in)
		if err != nil {
			return err
		}
		out = string(outBytes)
	case *encode:
		outBytes := snappy.Encode(nil, in)
		out = hex.EncodeToString(outBytes)
		if !*lower {
			out = strings.ToUpper(out)
		}
	}
	os.Stdout.WriteString(out)
	return err
}

func main() {
	if err := codec(); err != nil {
		os.Stderr.WriteString(err.Error() + "\n")
		os.Exit(1)
	}
}
